package com.umanji.enterprise;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.umanji.building.domain.Buildings;
import com.umanji.building.service.BuildingService;
import com.umanji.enterprise.domain.Enterprises;
import com.umanji.enterprise.domain.ServiceItems;
import com.umanji.enterprise.service.EnterpriseService;
import com.umanji.enterprise.service.SvcItemService;
import com.umanji.image.domain.Images;
import com.umanji.image.service.ImageService;

@Controller
@RequestMapping(value="/enterprise")
public class EnterpriseController {

	private Logger logger = org.slf4j.LoggerFactory.getLogger(EnterpriseController.class);

	private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	
	@Autowired
	public EnterpriseController(Validator validator) {
		this.validator = validator;
	}

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private BuildingService buildingService;

    @Autowired
    private SvcItemService svcItemService;

    @Autowired
    private ImageService imageService;

	@RequestMapping(value="/new", method=RequestMethod.GET)
	public ModelAndView getCreateForm(Model model) {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("account/createForm");
        mav.addObject("account", new Enterprises());
        return mav;
	}

	@RequestMapping(value="/create/{buildingNo}", method=RequestMethod.GET)
	public ModelMap createForm(@PathVariable String buildingNo, final HttpServletResponse response) {
		
		ModelMap mav = new ModelMap();

		Enterprises enterprise = new Enterprises();

		// enterprise.setServiceItems(svcItemService.findAll());

		mav.addAttribute("enterprise", enterprise);
		mav.addAttribute("svcitem", new ServiceItems());
		mav.addAttribute("buildingNo", buildingNo);
		mav.addAttribute("serviceItemList", svcItemService.findAll());
		return mav;
	}

	@RequestMapping(value = "/create/{buildingNo}", method = RequestMethod.POST)
	public String create(@PathVariable String buildingNo, @ModelAttribute("enterprise") Enterprises umanji_enterprise, BindingResult result, @RequestParam("serviceItemIds") Set<Long> serviceItemsIds, HttpServletRequest request) {
		logger.info("register umanji enterprise!");

		logger.info("service item id : " + serviceItemsIds );
		logger.info("sadkfjasfd : " + umanji_enterprise.getServiceItems());

        for (ConstraintViolation<Enterprises> constraint : validator.validate(umanji_enterprise)) {
            result.rejectValue(constraint.getPropertyPath().toString(), "", constraint.getMessage());
        }
        if (result.hasErrors())
        	return "/enterprise/create/" + buildingNo;

    	try {

			String rootPath = WebUtils.getRealPath(request.getSession().getServletContext(), "upload");

			List businessImgList = new ArrayList( ); 
			Images businessHoursImage = new Images(rootPath, umanji_enterprise.getSavedFileName(rootPath, umanji_enterprise.getBusinessHoursImageFileData(), "enterprise"));
			businessImgList.add(businessHoursImage);
			umanji_enterprise.setBusinessHoursImage(businessImgList);
			
			List enterpriseImgList = new ArrayList( ); 
			Images enterpriseImage = new Images(rootPath, umanji_enterprise.getSavedFileName(rootPath, umanji_enterprise.getEnterpriseImageFileData(), "enterprise"));
			enterpriseImgList.add(enterpriseImage);
			umanji_enterprise.setEnterpriseImage(enterpriseImgList);

    		Buildings building = buildingService.findByBuildingNo(buildingNo);
            umanji_enterprise.setBusinessSort("dslkafj");
            umanji_enterprise.setBuilding(building);

            enterpriseService.persist(umanji_enterprise);

    		List<ServiceItems> svcItems = new ArrayList( ); 
    		for(long svcItemId: serviceItemsIds) {
    			svcItems.add(svcItemService.find(svcItemId));
    		}
			umanji_enterprise.setServiceItems(svcItems);
			enterpriseService.merge(umanji_enterprise);
    	} catch (NoResultException e) {

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        return "redirect:/enterprise/create";
	}

	@RequestMapping(value="/create/{buildingNo}/svcitem", method=RequestMethod.GET)
	public ModelMap svcItemCreateForm(@PathVariable String buildingNo, final HttpServletResponse response) {

		ModelMap mav = new ModelMap();

		mav.addObject("svcitem", new ServiceItems());
		mav.addObject("buildingNo", buildingNo);
		return mav;
	}

	@RequestMapping(value = "/create/{buildingNo}/svcitem", method = RequestMethod.POST)
	public @ResponseBody String svcItemCreate(@PathVariable String buildingNo, @ModelAttribute("svcitem") ServiceItems umanji_svcitem, BindingResult result) {
		logger.info("register umanji enterprise service items!");

        for (ConstraintViolation<ServiceItems> constraint : validator.validate(umanji_svcitem)) {
            result.rejectValue(constraint.getPropertyPath().toString(), "", constraint.getMessage());
        }
        if (result.hasErrors())
        	return "/umj/enterprise/create/" + buildingNo;

        svcItemService.persist(umanji_svcitem);
        return "redirect:/umj/enterprise/create";
	}
}
